var AJAXRESULT_CODE_SUCCESS = "ok"
    , AJAXRESULT_CODE_ERROR = "error";
var layer, form, laytpl;

$(function(){
	initHeight();
	initLink();
	initPath();
	initLayui();
    reSetHeight();
    // ie不支持console.log 防止报错
	window.console = window.console || (function() {
		var c = {};
		c.log = c.warn = c.debug = c.info = c.error = c.time = c.dir = c.profile= c.clear = c.exception = c.trace = c.assert = function(){};
		return c;
	})();
    $(".m-portlet").mCustomScrollbar({
        axis:"y"
    });
});

function initLayui() {
    layer = layui.layer;
    form = layui.form;
    laytpl = layui.laytpl;
}
function initPath(){
	var localObj = window.location;
	var contextPath = localObj.pathname.split("/")[1];
	basePath = localObj.protocol+"//"+localObj.host+"/"+contextPath;
}

function initHeight(){
    var topHeight = 120;
    var padding = 40;
    var winHeight = $(window).height();
    var mainFrameHeight = winHeight-topHeight-padding;
}

function initLink(){
	$(".m-menu__link").on("click",function(ev){
		ev.preventDefault();
	var target = $(this).attr("href");
		if(target!='javascript:void(0);'){
            // $("#menu-title").html($(this).text());
            $("#mainFrame").attr("src", target);

        }
    })
    //个人信息
    $("#personDetail").on("click", function (ev) {
        ev.preventDefault();
        $("#mainFrame").attr("src", basePath + "/user/detailPage");
    })
    //密码修改
    $("#editPasswordPage").on("click", function (ev) {
        layer.open({
            title: '修改密码',
            type: 1,
            maxmin: true,
            area: ['50%', '50%'],
            shadeClose: true,
            scrolling: false,
            content: $("#passwordHtml").html(),
            success: function (layero, index) {
                //确认修改
                $("#editYes").on('click', function () {
                    var oldWord = $("#old_Word").val();
                    var newWord = $("#new_Word").val();
                    var confirmWord = $("#confirm_Word").val();
                    //密码校验
                    if (newWord != confirmWord) {
                        layer.msg("新密码与确认密码不一致");
                        return;
                    }
                    if (!(/^.*(?=.*\d)(?=.*[A-Z])(?=.*[a-z])(?![.\n])(?!.*\s)^.{8,20}$/.test(newWord)
                        && /^.*(?=.*\d)(?=.*[A-Z])(?=.*[a-z])(?![.\n])(?!.*\s)^.{8,20}$/.test(confirmWord))) {
                        layer.msg("密码大于8位小于20位，必须包含大小写字母和数字");
                        return;
                    }
                    //保存
                    var param = {
                        oldWord: oldWord,
                        newWord: newWord,
                        confirmWord: confirmWord,
                        id: $('#userId').val()
                    };
                    $.hcPostAjax({
                        showLoad: true,
                        url: basePath + '/wQyUser/updateWord',
                        data: param,
                        success: function (data) {
                            layer.msg('密码修改成功,请重新登陆！', {
                                icon: 1, time: 1800
                            }, function () {
                                logout();//注销当前用户
                            });
                        },
                        error: function () {
                            layer.msg('更新失败');
                        }
                    });
                });
                //取消
                $("#editCancle").on("click", function () {
                    layer.closeAll();
                });
            }
        });
    })
}

/**
 * 获取mDatatable插件初始化参数
 * @param url
 * @param columns
 * @returns {{data: {type: string, source: {read: {url: *, method: string, params: {status: number}, map: (function(*): *)}}, saveState: {cookie: boolean, webstorage: boolean}, pageSize: number, serverPaging: boolean, serverFiltering: boolean, serverSorting: boolean}, layout: {scroll: boolean, footer: boolean}, sortable: boolean, pagination: boolean, toolbar: {items: {pagination: {pageSizeSelect: number[]}}}, translate: {records: {processing: string, noRecords: string}, toolbar: {pagination: {items: {default: {first: string, prev: string, next: string, last: string, more: string, input: string, select: string}, info: string}}}}, columns: *}}
 */
function getMDatatableOption(url, params, columns, height) {
    var bodyHeight = $(document.body).height();
    var searchDivHeight =$(".m-form--label-align-right").height();
    var height;
    if(isEmpty(searchDivHeight)){
        height = 400;
    }else {
        height = bodyHeight-searchDivHeight-85;
    }
    if(height<bodyHeight*0.58){
        height=bodyHeight*0.58;
    }

    $.each(columns, function (i) {
        if (this.sortable == undefined) {
            this.sortable = false;
        }
    })
    return {
        data: {
            type: "remote",
            source: {
                read: {
                    url: url,
                    method: 'GET',
                    params: params,
                    map: function (raw) {
                        return raw.rows == null ? (raw.data == null ? [] : raw.data) : raw.rows;
                    }
                }
            },
            saveState: {
                cookie: false,
                webstorage: false
            },
            pageSize: 20,
            serverPaging: true,
            serverFiltering: !0,
            serverSorting: !0
        },
        layout: {
            scroll: true,
            footer: !1,
            height:height,
            minHeight: height == undefined ? $("body").height() * 0.68 : height
        },
        sortable: !0,
        pagination: !0,
        toolbar: {
            items: {
                pagination: {
                    pageSizeSelect: [10, 20, 30, 50, 100, 1000]
                }
            }
        },
        translate: {
            records: {
                processing: "正在加载中...",
                noRecords: "暂无记录"
            },
            toolbar: {
                pagination: {
                    items: {
                        default: {
                            first: '首页',
                            prev: '前一页',
                            next: '下一页',
                            last: '末页',
                            more: '更多页',
                            input: '页数',
                            select: '请选择每页多少条'
                        },
                        info: '展示 {{start}} - {{end}} 条，共 {{total}} 条记录'
                    }
                }
            }
        },
        columns: columns
    };
}

/**
 * 获取一个table column中按钮
 * clazz: '', title: '', icon: '', id: '', name: '', click: 'void(0)'
 * {
 * 	clazz 样式，用于绑定事件
 * 	title 鼠标悬浮提示文字
 * 	icon 显示的图标（line-awesome）
 * 	id 该行数据的id
 * 	name 该行数据的name
 * 	click 点击事件
 * }
 * @returns {string}
 */
function getColumnButton(options) {
	var baseOptions = {
			clazz: 'm-btn--hover-accent editBtn',
			title: '',
			icon: '',
			id: '',
			name: '',
			click: 'void(0)'
	}
	$.extend(baseOptions, options);
    var columnButton = '<a href="javascript:{{CLICK}};" class="m-portlet__nav-link btn m-btn m-btn--icon m-btn--icon-only m-btn--pill {{CLAZZ}}" data-id="{{ID}}" data-name="{{NAME}}" title="{{TITLE}}"><i class="{{ICON}}"></i></a>';
    return columnButton.replace('{{CLAZZ}}', baseOptions.clazz)
    	.replace('{{TITLE}}', baseOptions.title)
    	.replace('{{ICON}}', baseOptions.icon)
    	.replace('{{ID}}', baseOptions.id)
    	.replace('{{NAME}}', baseOptions.name)
    	.replace('{{CLICK}}', baseOptions.click);
}

/**
 * 获取列表已选数据
 * @param datatable
 * @returns {Array}
 */
function getMDatatableSelectedRow(datatable) {
    var dateSet = datatable.dataSet;
    var selectedRows = [];
    $.each(datatable.getSelectedRecords(), function(i) {
        selectedRows.push(dateSet[this.dataset.row]);
    })
    return selectedRows;
}

/**
 * 获取选中列的id值
 * @param datatable
 * @returns {Array}
 */
function getMDatatableSelectedIds(datatable) {
    var ids = [];
    datatable.getSelectedRecords().each(function(){
        ids.push($($(this).find("td:first-child [type='checkbox']")).val());
    });
    return ids;
}

/**
 * 获取选中列的columnName值
 * @param datatable
 * @param columnName
 * @returns {Array}
 */
function getMDatatableSelectedColumns(datatable, columnName) {
    var values = [];
    datatable.getSelectedRecords().each(function(){
        values.push($($(this).find("td[data-field='" + columnName + "'] span")).text());
    });
    return values;
}

/**
 * 获取id行的row值对象
 * @param datatable
 * @param id
 * @param idColumn
 * @returns {*}
 */
function getMDatatableRow(datatable, id, idColumn) {
    var data = datatable.getDataSet();
    for (var i = 0; i < data.length; i++) {
        if (data[i][idColumn] == id) {
            return data[i];
        }
    }
}
/**
 * 获取多行row值对象
 * @param datatable
 * @param id
 * @param idColumn
 * @returns {*}
 */
function getMDatatableRows(datatable, ids, idColumn) {
	var columVal=[];
    var data = datatable.getDataSet();
    for(var j=0;j<ids.length;j++){
    	var id=ids[j];
    	  for (var i = 0; i < data.length; i++) {
    	        if (data[i]["id"] == id) {
    	        	columVal.push(data[i][idColumn]);
    	        }
    	    }
    }
  return columVal;
}

/**
 * 列表查询
 * @param datatable
 * @param param 参数对象
 */
function queryMDatatable(datatable, param) {
    datatable.setDataSourceParam("query", param);
    datatable.load();
}

/**
 * 表格设置成只能单选
 * 注意：该datatable的tableColumns中的复选框field需有唯一值
 * @param datatable
 */
function setMDatatableSingleSelect(datatable) {
    // 设置全选框失效
    datatable.on("m-datatable--on-init", function(e, options) {
        datatable.find("label.m-checkbox--all input").attr("disabled", "true");
    })

    var checkField = datatable.find("thead tr th:first").attr("data-field");// 勾选框的字段名
    // 勾选时，将以前的设置成不选
    datatable.on('m-datatable--on-check', function(e, obj) {
        // 将之前选择的设置成不选
        var selectRows = getMDatatableSelectedRow(datatable);
        if (!isEmpty(selectRows)) {
            $.each(selectRows, function(i) {
                if (selectRows[i][checkField] != obj[0]) {
                    datatable.setInactive(selectRows[i][checkField]);
                }
            })
        }
    })
}

/**
 * form表单渲染
 * 支持：input——type为text/checkbox/radio
 * 	     select——select2单选/多选，或者普通的select都可以
 *       textarea
 * @param selector
 * @param data
 * @returns
 */
function renderFormData(selector, data) {
	for (var name in data) {
		var value = data[name];
		var tag = $(selector).find("[name=" + name + "]");
		switch (tag.prop("tagName")) {
		case "INPUT":
			var type = tag.attr("type");
			if (type == "text" || type == undefined || type=="number") {
				tag.val(value);
			} else if (type == "checkbox") {
				if (!!value) {
					value.split(",").each(function(i) {
						$(selector).find("[name=" + name + "][value=" + value + "]").prop("checked", true).trigger("change");
					})
				}
			} else if (type == "radio") {
				$(selector).find("[name=" + name + "][value=" + value + "]").prop("checked", true).trigger("change");
			}
			break;
		case "SELECT":
			if (!!value) {
				tag.val((value + "").split(",")).trigger("change");
			}
			break;
		case "TEXTAREA":
			tag.val(value);
			break;
		default: 
			tag.val(value);
		}
	}
}

/**
 * form表单获取值
 * 支持元素: input——type=text/radio/checkbox
 * 			 select
 *           textarea
 * @param selector
 * @returns
 */
function getFormData(selector) {
	var formData = {};
	$.each($(selector).find("[name]"), function(i) {
		var name = $(this).attr("name");
		// 如果已经有值了，就忽略当前元素
		if (formData[name] != undefined || isEmpty(name)) {
			return true;
		}
		switch(this.tagName) {
		case "INPUT":
			var type = $(this).attr("type");
			if (type=="text" || type=="number") {
				formData[name] = $(this).val().trim();
			} else if (type=="checkbox") {
				var valueArray = [];
				var checkedAll = $(selector).find("input[name=" + name + "]:checked");
				$.each(checkedAll, function(i) {
					valueArray.push($(this).val());
				})
				if (valueArray.length > 0) formData[name] = valueArray.join(",");
			} else if (type=="radio") {
				formData[name] = $(selector).find("input[name=" + name + "]:checked").val();
			}
			break;
		case "SELECT":
			formData[name] = $(this).val();
			break;
		case "TEXTAREA":
			formData[name] = $(this).val().trim();
			break;
		}
	})
	return formData;
}

/**
 * 根据id从form表单获取值
 * 支持元素: input——type=text/radio/checkbox
 * 			 select
 *           textarea
 * @param selector
 * @returns
 */
function getFormDataById(selector) {
    var formData = {};
    $.each($(selector).find("[name]"), function(i) {
        var name = $(this).attr("id");
        // 如果已经有值了，就忽略当前元素
        if (formData[name] != undefined || isEmpty(name)) {
            return true;
        }
        switch(this.tagName) {
            case "INPUT":
                var type = $(this).attr("type");
                if (type=="text" || type=="number") {
                    formData[name] = $(this).val().trim();
                } else if (type=="checkbox") {
                    var valueArray = [];
                    var checkedAll = $(selector).find("input[id=" + name + "]:checked");
                    $.each(checkedAll, function(i) {
                        valueArray.push($(this).val());
                    })
                    if (valueArray.length > 0) formData[name] = valueArray.join(",");
                } else if (type=="radio") {
                    formData[name] = $(selector).find("input[id=" + name + "]:checked").val();
                }
                break;
            case "SELECT":
                formData[name] = $(this).val();
                break;
            case "TEXTAREA":
                formData[name] = $(this).val().trim();
                break;
        }
    });
    return formData;
}

/**
 * 获取url参数
 * @param name
 * @returns
 */
function getUrlParam(name) {
	var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i"); 
	var r = window.location.search.substr(1).match(reg); 
	if (r != null) return unescape(r[2]); return null; 
}

/**
 * 日期的格式化
 * 调用示例：
 * var time1 = new Date().Format("yyyy-MM-dd"); 
 * var time2 = new Date().Format("yyyy-MM-dd hh:mm:ss");
 */
Date.prototype.Format = function (fmt) { 
	var o = {
		"M+": this.getMonth() + 1, //月份
		"d+": this.getDate(), //日
		"h+": this.getHours(), //小时
		"m+": this.getMinutes(), //分
		"s+": this.getSeconds(), //秒
		"q+": Math.floor((this.getMonth() + 3) / 3), //季度
		"S": this.getMilliseconds() //毫秒
	};
	if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
	for (var k in o)
	if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
	return fmt;
}

/**
 * 展示ajax错误信息，需要手动触发关闭，便于查看错误原因
 * @param msg
 */
function showAjaxErrorMsg(msg, feedback) {
    if (jQuery.isFunction(feedback)) {
        layer.msg(msg, {
                icon: 2, time: 0, closeBtn: true
            }, feedback
        );
    } else {
        layer.msg(msg, {
                icon: 2, time: 0, closeBtn: true
            }
        );
    }
}

/**
 * 删除数组中匹配到的第一个元素
 * @param array
 * @param item
 */
function arrayDeleteItem(array, item) {
    var index = $.inArray(item, array);
    if (index >= 0) {
        array.splice(index, 1);
    }
}

/**
 * 判断是否为空
 * @param a
 * @returns
 */
function isEmpty(a) {
    return !$.trim(a);
}

function isEmptyOrUndef(a){
	return !$.trim(a) || a == undefined;
}

/**
 * 页面跳转加上agentid
 * @param url
 * @returns
 */
function hcPageForward(url) {
	window.location = url;
}

/**
 * 格式化JSON数据展示
 * @param json
 * @returns {*}
 */
function syntaxJSON(json) {
    if (typeof json != 'string') {
        return JSON.stringify(json, undefined, 4);
    }
    return JSON.stringify(parse_json_by_eval(json), undefined, 4);
}

/**
 * 字符串转JSON格式
 * @param str
 * @returns {any}
 */
function parse_json_by_eval(str){
    str = $.trim(str);
    return eval('('+str+')');
}

/**
 * 判断是否是json格式
 * @param str
 * @returns {*}
 */
function isJSON(str) {
    try {
        var obj = parse_json_by_eval(str);
        return !!obj && (typeof obj === 'undefined' ? 'undefined' : typeof obj) === 'object';
    } catch (e) {/* ignore */}
    return false;
}

/**
 * 设置页面高度
 */
function reSetHeight() {
    var obj = parent.document.getElementsByClassName("m-aside-left");//取得父页面IFrame对象
    var height = $(obj).height();
    var parentHeight = $(parent.document.getElementsByClassName("m-aside-left")).height();
    var headerHeight = $(parent.document.getElementsByClassName("m-stack--desktop")).height();
    $(parent.document.getElementsByName("mainFrame")).css('height', parentHeight - headerHeight - 40 + 'px');
}

/**直接下载图片，不是直接打开图片*/
function downLoadPicture(url){
	var $a = document.createElement('a');
	    $a.setAttribute("href", url);
	    $a.setAttribute("download", "");
	    var evObj = document.createEvent('MouseEvents');
	    evObj.initMouseEvent( 'click', true, true, window, 0, 0, 0, 0, 0, false, false, true, false, 0, null);
	    $a.dispatchEvent(evObj);
}
/**检验是否是纯数字*/
function isNumber(val){
    var regPos = /^\d+(\.\d+)?$/; //非负浮点数
   // var regNeg = /^(-(([0-9]+\.[0-9]*[1-9][0-9]*)|([0-9]*[1-9][0-9]*\.[0-9]+)|([0-9]*[1-9][0-9]*)))$/; //负浮点数
    if(regPos.test(val)){
        return true;
    }else{
        return false;
    }

}
/**
 * 弹出提示信息并返回false
 * @param msg
 * @param _id
 * @returns {boolean}
 */
function alertMsg(msg, _id) {
    if (_id) {
        $('#' + _id).focus();
    }
    layer.msg('<span style="font-weight: bold;">' + msg + "</span>",{icon:5,shift:6});
    return false;
}

/**
 * 弹出提示信息并返回false
 * @param msg
 * @param selector 表单的选择器
 * @returns
 */
function alertSMsg(msg, selector) {
    if (selector) {
        $(selector).focus();
    }
    layer.msg(msg,{icon:5,shift:6});
    return false;
}
/**
 * 构建导出链接
 * @param url
 * @param param
 * @returns {*}
 */
function buildExportUrl(url, param) {
    var paramKeys = Object.keys(param);
    if (paramKeys.length == 0) return url;

    // 去除无效参数
    var trueParam = {};
    for (var i = 0; i < paramKeys.length; i++) {
        if (param[paramKeys[i]] !== undefined && param[paramKeys[i]] !== null && param[paramKeys[i]] !== '') {
            trueParam[paramKeys[i]] = param[paramKeys[i]];
        }
    }

    var trueParamKeys = Object.keys(trueParam);
    if (trueParamKeys.length == 0) return url;
    for (var j = 0; j < trueParamKeys.length; j++) {
        if (j == 0) {
            url += "?";
        }
        url += trueParamKeys[j] + "=" + trueParam[trueParamKeys[j]];
        if (j < trueParamKeys.length - 1) {
            url += "&";
        }
    }
    return url;
}

/**
 * 1、大小写转换，中文输入法下，仅在选词后触发input事件；2、光标定位
 * @param selector
 */
function inputUpper(selector) {
    var typing = false;
    $(selector).on('compositionstart',function(){
        typing = true;
    });
    $(selector).on('compositionend',function(){
        typing = false;
        var value = $(this).val();
        var start = this.selectionStart;
        var end = this.selectionEnd;
        $(this).val(value.toUpperCase());
        this.setSelectionRange(start, end);
        return false;
    });
    $(selector).on('input', function () {
        if (!typing) {
            var value = $(this).val();
            var start = this.selectionStart;
            var end = this.selectionEnd;
            $(this).val(value.toUpperCase());
            this.setSelectionRange(start, end);
        }
    });
}

//航班日期加载并设置为当前时间
function initFdateWithNow(selector) {
    $(selector).datetimepicker({
        language: 'zh-CN',
        format: 'yyyymmdd',
        todayHighlight: true,
        autoclose: true,
        minView: 2,
        forceParse: 0,
        pickerPosition: 'bottom-right'
    });
    //设置默认当前时间
    $(selector).val(new Date().Format('yyyyMMdd'));
}


function isNotEmpty(a) {
    var jsonStringify = true;
    try {
        //JSON.stringify 会报错，抓下异常
        jsonStringify = JSON.stringify(a) != '{}' ? true : false;
    } catch (e) {
        //nothing
    }
    return !isEmpty(a) && a != undefined && jsonStringify;
}